/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(const vector<int>& inorder, const vector<int>& postorder, int& post, int left, int right)
    {
        if (left > right)
            return nullptr;
        TreeNode* root = new TreeNode(postorder[post]);
        int mid = left;
        while (mid < right)
        {
            if (postorder[post] == inorder[mid])
                break;
            mid++;
        }
        post--;
        root->right = _buildTree(inorder, postorder, post, mid + 1, right);
        root->left = _buildTree(inorder, postorder, post, left, mid - 1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int post = postorder.size() - 1;
        return _buildTree(inorder, postorder, post, 0, inorder.size() - 1);
    }
};